package com.zhang.crawler.servlet;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.jsoup.Jsoup;
import org.jsoup.select.Elements;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/DoServlet")
public class DoServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	public DoServlet() {
		super();
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//获取每个商城的商品的价格
		String key = request.getParameter("key");	//从页面中获取参数
		//解决中文乱码，提交方式post，内部网页编码（传输）编码都是iso-8859-1
		key = new String(key.getBytes("iso-8859-1"),"utf-8");

		//200, 152, 100

		String pricestr = getJDPrice(key) + "," + getTBPrice(key) + "," +getSNPrice(key);
		//传递到后面的jsp页面
		request.setAttribute("pricestr", pricestr);

		request.getRequestDispatcher("/WEB-INF/views/result.jsp").forward(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

	public String getJDPrice(String key){
		//1.请求京东查询页面
		//https://search.jd.com/Search?keyword=iphonex%2064g%20%E9%BB%91%E8%89%B2
		key = key.replaceAll(" ", "%20");
		String url = "https://search.jd.com/Search?keyword="+key;
		try{
			//2.利用jsoup获取商品链接
			Elements els = Jsoup.connect(url).get()
					.select(".p-img a");
			//https://item.jd.com/5089253.html
			String itemUrl = els.get(0).attr("href");

			//3.解析itemId商品id号
			int beginPos = itemUrl.lastIndexOf("/")+1;	//开始位置
			int endPos = itemUrl.lastIndexOf(".");
			String itemId = itemUrl.substring(beginPos, endPos);

			//4.抓取商品的价格 json
			String priceUrl = "http://p.3.cn/prices/mgets?skuIds=J_"+itemId;
			String json = Jsoup.connect(priceUrl).ignoreContentType(true).execute().body();

			//5.处理Json从中获取price
			ObjectMapper MAPPER = new ObjectMapper();
			JsonNode node = MAPPER.readTree(json);
			String price = node.get(0).get("p").asText();

			return price;
		}catch(Exception e){
			return "";		//如果返回值是空代表异常
		}
	}

	public Double getTBPrice(String key){
		return 6000.0;
	}

	public Double getSNPrice(String key){
		return 6500.0;
	}
}





